package com.netease.nie.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netease.nie.base.exceptions.BusinessException;
import com.netease.nie.base.utils.CopyUtils;
import com.netease.nie.constants.BusinessConstants;
import com.netease.nie.dao.GoodsInfoImageDao;
import com.netease.nie.dto.GoodsInfoImageDto;
import com.netease.nie.model.GoodsInfoImage;

@Service
public class GoodsInfoImageServiceImpl implements GoodsInfoImageService {

	@Autowired
	private GoodsInfoImageDao goodsInfoImageDao;
	
	private Map<Integer, List<GoodsInfoImage>> combineGoodsInfoImageResult(List<GoodsInfoImage> goodsInfoImageList) {
		if (!goodsInfoImageList.isEmpty()) {
			int goodsInfoImageListSize = goodsInfoImageList.size();
			GoodsInfoImage goodsInfoImage = null;
			Map<Integer, List<GoodsInfoImage>> map = new HashMap<Integer, List<GoodsInfoImage>>();
			List<GoodsInfoImage> goodsInfoImageTempList = null;
			for (int i = 0; i < goodsInfoImageListSize; i++) {
				goodsInfoImage = goodsInfoImageList.get(i);
				int goodsId = goodsInfoImage.getGoodsId();
				if (map.containsKey(goodsId))
					goodsInfoImageTempList = map.get(goodsId);
				else
					goodsInfoImageTempList = new ArrayList<GoodsInfoImage>();
				goodsInfoImageTempList.add(goodsInfoImage);
				map.put(goodsId, goodsInfoImageTempList);
			}
			return map;
		}
		return Collections.emptyMap();
	}

	public List<GoodsInfoImageDto> queryGoodsInfoImageDtosByGoodsId(int goodsId) {
		List<GoodsInfoImage> goodsInfoImages = goodsInfoImageDao.queryGoodsInfoImagesByGoodsId(goodsId);
		if (goodsInfoImages != null && !goodsInfoImages.isEmpty()) {
			int goodsInfoImagesSize = goodsInfoImages.size();
			GoodsInfoImage goodsInfoImage = null;
			GoodsInfoImageDto goodsInfoImageDto = null;
			List<GoodsInfoImageDto> goodsInfoImageDtos = new ArrayList<>();
			for (int i = 0; i < goodsInfoImagesSize; i++) {
				goodsInfoImage = goodsInfoImages.get(i);
				goodsInfoImageDto = new GoodsInfoImageDto();
				CopyUtils.copy(goodsInfoImageDto, goodsInfoImage);
				goodsInfoImageDtos.add(goodsInfoImageDto);
			}
			return goodsInfoImageDtos;
		}
			
		return Collections.emptyList();
	}

	public GoodsInfoImage queryCoverGoodsImageByGoodsId(int goodsId) {
		GoodsInfoImage goodsInfoImage = goodsInfoImageDao.queryCoverImageByGoodsId(goodsId);
		if (goodsInfoImage == null)
			throw new BusinessException(BusinessConstants.GOODS_IMAGE_NOT_EXISTS.getCode(), "商品图片不存在");
		return goodsInfoImage;
	}
}
